<?php

class UsersController extends AppController {

	var $name = 'Users';
	var $paginate = array();
	function index() {
		$this->redirect('mypage');
	}
	
	public function beforeFilter() {
		parent::beforeFilter();
		$this->CustomAuth->allow('signup' , 'signin', 'facebookSignup', 'facebookNew', 'reminder', 'admin_signin', 'facebook');
	}

	/*
	 * signin action
	 */
	function signin() {
		if ($this->RequestHandler->isAjax()) {
			$result = array(
				'status' => false,
				'error' => array(
					'type' => 'user_not_login',
					'url' => Router::url(),
				)
			);
			$this->set('json', $result);
			return $this->render('/elements/json', 'ajax');
		}
		$this->_checkLogin();
		Configure::load('facebook');
		$facebook = $this->_getFacebookObject();
		$params = array(
			'redirect_uri' => Configure::read('facebook.redirectUrl')
		);
		$this->set('facebookLoginUrl', $facebook->getLoginUrl($params));
		$this->Session->write('signupAction', 'login');
		$this->loadModel('LoginForm');
		$this->loadModel('User');
		if(!empty($this->data)){
			$data = array('email' => $this->data['LoginForm']['email'], 'password' => $this->data['LoginForm']['password']);
			if($this->CustomAuth->login($data)){
				$this->loadModel('Profile');
				$user = $this->CustomAuth->user();
				$profile = $this->Profile->find('first', array('conditions' => array('user_id' => $user['User']['id'])));
				$sessionData = array(
					'userName' => $profile['Profile']['last_name'].' '.$profile['Profile']['first_name'],
					'iconImage' => $profile['Profile']['icon_image'] ? $profile['Profile']['icon_image'] : '',
					'loginType' => Configure::read('loginType.email'),
					'profileId' => $profile['Profile']['id'],
					'headline'	=> $profile['Profile']['headline'],
				);
				$this->_setLoginSession($sessionData);
				$this->_successRedirect();

			}else{
				$this->Session->setFlash(Messages::invalid_account_specified, '');
			}
		}else {
			$this->Session->write('referUrl', env('HTTP_REFERER'));
		}
		$this->set(array(
			'title_for_layout' => 'ログイン - Adams Campus'
		));
	}

    /**
     * signup action
     */
	function signup() {
		$this->_checkLogin();
		$this->loadModel('User');
		$this->loadModel('SignupForm');
		Configure::load('facebook');
		$facebook = $this->_getFacebookObject();
		$params = array(
			'redirect_uri' => Configure::read('facebook.redirectUrl')
		);
		$this->set(array('facebookLoginUrl' => $facebook->getLoginUrl($params), 'title_for_layout' => '新規会員登録'));
		$this->Session->write('signupAction', 'login');
		if (!empty($this->data)) {
			$this->SignupForm->set($this->data);
			if ($this->SignupForm->validates()) {
				$this->User->set('email', $this->data['SignupForm']['email']);
				$this->User->set('password', $this->CustomAuth->password($this->data['SignupForm']['password']));
				$this->User->set('mailmagazine_flg', 0);
				$this->User->set('profile_setting', 0);
				$this->User->set('del_flag', 0);
				$this->User->set('created', date('Y-m-d H:i:s'));
				$this->User->set('modified', date('Y-m-d H:i:s'));
				$this->User->set('role', 'user');//add 2012/03/04
				unset($this->User->validate['password']);
				$dataSource = $this->User->getDataSource();
				$dataSource->begin($this->User);
				if ($this->User->save()) {
					$this->loadModel('Profile');
					$data = array(
						'user_id' => $this->User->id,
						'first_name' => trim(htmlspecialchars($this->data['SignupForm']['first_name'])),
						'last_name' => trim(htmlspecialchars($this->data['SignupForm']['last_name'])),
						'headline' => '',
						'icon_image' => '',
						'del_flg' => 0,
						'created' => date('Y-m-d H:i:s'),
						'modified' => date('Y-m-d H:i:s')
							);
					if($this->Profile->save($data, false)){
						$dataSource->commit($this->User);
						$this->_sendUserEmail($data['last_name'].' '. $data['first_name'], $this->data['SignupForm']['email']);
						$dataLogin = array('email' => $this->data['SignupForm']['email'], 'password' => $this->data['SignupForm']['password']);
						if($this->CustomAuth->login($dataLogin)){
							$sessionData = array(
								'userName' => $data['last_name'].' '.$data['first_name'],
								'iconImage' => $data['icon_image'],
								'loginType' => Configure::read('loginType.email'),
								'profileId' => $this->Profile->id,
								'headline'	=> $data['headline']
							);
							$this->_setLoginSession($sessionData);
							$this->_successRedirect();
						}
						else{
							$this->Session->setFlash(Messages::error_please_try_again);
							$this->redirect('signin');
						}
					}else{
						$dataSource->rollback($this->User);
					}

					$this->redirect('/');
				}else{
					$dataSource->rollback($this->User);
				}
			} else {
				//var_dump($this->SignupForm->validationErrors);
			}
		} else {
			$this->Session->write('referUrl', env('HTTP_REFERER'));
		}
		$this->set(array(
			'title_for_layout' => '新規登録 - Adams Campus'
		));
	}

	function facebookSignup() {
		if (isset($this->params['url']['error']) || isset($this->params['url']['error_reason'])) {
			$this->redirect('/');
		}
		if (!isset($this->params['url']['state']) && !isset($this->params['url']['code'])) {
			$this->redirect('/');
		}
		Configure::load('facebook');
		if ($this->Session->read('signupAction') == 'logout') {
			$this->redirect('/');
		}

		$userId = null;
		$facebook = $this->_getFacebookObject();
		$userId = $facebook->getUser();
		if ($userId) {
			try {
				$userInfo = $facebook->api('/' . $userId);
				$result = $this->User->findByFacebookUserId($userInfo['id']);
				if ($result) {
					//set login session and redirect to index page
					$dataLogin = array(
						'facebook_user_id' => $userInfo['id']
					);
					if($this->CustomAuth->login($dataLogin)){
						$sessionData = array(
								'userName' => $result['Profile']['last_name'].' '. $result['Profile']['first_name'],
								'iconImage' => $result['Profile']['icon_image'] ? $result['Profile']['icon_image'] : '',
								'loginType' => Configure::read('loginType.facebook'),
								'profileId' => $result['Profile']['id'],
								'headline' => $result['Profile']['headline']
						);
						$this->_setLoginSession($sessionData);
						$this->_successRedirect();
					}else{
						$this->Session->setFlash(Messages::cant_login_by_facebook_please_try_again);
						$this->redirect('signin');
					}
					
				} else {
					$this->redirect('facebookNew');
				}
			} catch (Exception $ex) {
				//
			}
		} else {
			$params = array(
				'redirect_uri' => Configure::read('facebook.redirectUrl')
			);
			$this->redirect($facebook->getLoginUrl($params));
		}
		$this->redirect('/');
	}


	/*
	 * sub step : input email after sigup by facebook
	 */

	function facebookNew() {
		$this->_checkLogin();
		Configure::load('facebook');
		if (!empty($this->data)) {
			$this->User->set($this->data);
			$this->User->set('password', $this->CustomAuth->password($this->data['User']['email'] . uniqid()));
			unset($this->User->validate['password']);
			if ($this->User->validates() && $this->data['Facebook']['term'] == '1' ) {
				$facebook = $this->_getFacebookObject();
				$userId = $facebook->getUser();
				if ($userId) {
					try {
						$userInfo = $facebook->api('/' . $userId);
						$result = $this->User->findByFacebookUserId($userInfo['id']);
						if (!$result) {
							$this->User->set('facebook_user_id', $userInfo['id']);
							$this->User->set('facebook_access_token', $facebook->getAccessToken());
							$this->User->set('del_flag', 0);
							$this->User->set('created', date('Y-m-d H:i:s'));
							$this->User->set('modified', date('Y-m-d H:i:s'));
							$this->User->set('role', 'user');//add 2012/03/04
							$dataSource = $this->User->getDataSource();
							$dataSource->begin($this->User);
							if ($this->User->save()) {
								$this->loadModel('Profile');
								// get facebook avatar
								$facebookUrl = Configure::read('User.facebook_avatar').$userInfo['username'].'/picture?redirect=false&type=large';
								$avatarDir = Configure::read('User.upload_dir_prefix').DS.$this->User->id;
								$localUrl = $this->_getFacebookAvatar($facebookUrl, $avatarDir, $this->User->id);
								$data = array(
									'user_id' => $this->User->id,
									'first_name' => $userInfo['first_name'],
									'last_name' => $userInfo['last_name'],
									'headline' => '',
									'icon_image' => $localUrl,
									'del_flg' => 0,
									'created' => date('Y-m-d H:i:s'),
									'modified' => date('Y-m-d H:i:s')
										);
								unset($this->Profile->validate['first_name']);
								unset($this->Profile->validate['last_name']);
								unset($this->Profile->validate['headline']);
								if($this->Profile->save($data)){	
									$dataSource->commit($this->User);
                                    $this->_sendUserEmail($data['last_name'].' '. $data['first_name'], $this->data['User']['email']);
									$dataLogin = array(
										'facebook_user_id' => $userInfo['id']
									);
									if($this->CustomAuth->login($dataLogin)){
										$sessionData = array(
												'userName' => $userInfo['last_name'].' '.$userInfo['first_name'] ,
												'iconImage' => $localUrl,
												'loginType' => Configure::read('loginType.facebook'),
												'profileId' => $this->Profile->id,
												'headline' => $data['headline']
										);
										$this->_setLoginSession($sessionData);
										$this->_successRedirect();
									}else{
										$this->Session->setFlash(Messages::error_please_try_again);
										$this->redirect('signin');
									}
								}else{
									$dataSource->rollback($this->User);
								}
								$this->redirect('/');
								
							}else{
								$dataSource->rollback($this->User);
							}
						} else {
							//set login session and redirect to index page
							$this->redirect('/');
						}
					} catch (Exception $ex) {
					}
				} else {
					$this->redirect('signup');
				}
			}else if( $this->data['Facebook']['term'] != '1'){
				$this->set('errorMessage', Messages::term_of_service);
			}
		}
		$this->set(array(
			'title_for_layout' => 'メールアドレスの登録 - Adams Campus'
		));
	}

	/*
	 * set login session infor
	 */
	function _setLoginSession($data){
		try{
			$this->Session->write('loginStatus', 'login');
			$this->Session->write('loginType', $data['loginType']);
			$this->Session->write('User.name', $data['userName']);
			$this->Session->write('User.headline', $data['headline']);
			if(isset($data['profileId'])){
				$this->Session->write('User.profileId', $data['profileId']);
			}else{
				$this->Session->write('User.profileId', -1);
			}
			if($data['iconImage'] != ''){
				$this->Session->write('User.icon_image', $data['iconImage']);
			}else{
				$this->Session->write('User.icon_image', '');
			}
		}
		catch(Exception $ex){
			throw $ex;
		}
	}
	
	/*
	 * logout action
	 */
	function logout() {
		Configure::load('facebook');
		$this->Session->delete('loginStatus');
		$this->Session->write('signupAction', 'logout');
		$this->Session->delete('User');
		$this->CustomAuth->logout();
		if (($this->Session->read('loginType') == Configure::read('loginType.facebook'))) {
			$facebook = $this->_getFacebookObject();
			$userId = $facebook->getUser();
			$userInfo = $facebook->api('/' . $userId);
			$this->Session->delete('loginType');
			if ($userInfo) {
				$logoutUrl = $facebook->getLogoutUrl(array('next' => Configure::read('facebook.redirectUrl')));
				$this->redirect($logoutUrl);
			}
		} else {
			$this->Session->delete('loginType');

		}
		$this->redirect('/');
	}
	
	/*
	 * action mypage
	 */
	function mypage() {
		$user = $this->Session->read($this->CustomAuth->sessionKey);
		Configure::load('file');
		$this->loadModel('EnteredCourse');
		$this->loadModel('Area');
		$this->loadModel('Category');
		$options['fields'] = array('Course.id', 'Course.user_id', 'Course.course_type', 'Course.category',' Course.course_image01','Course.title','Course.description',
			'CoursesDetail.opening_date', 'CoursesDetail.closing_date', 'CoursesDetail.area', 'CoursesDetail.attend_total', 'CoursesDetail.notice', 'CoursesDetail.course_id',
			'CoursesDetail.place_name','Profiles.first_name', 'Profiles.last_name',	'Profiles.icon_image');//
		$options['limit'] = 9;
		$options['joins'] = array(
			array(
				'table' => 'courses_detail',
				'alias' => 'CoursesDetail',
				'type' => 'inner',
				'conditions' => array(
					'EnteredCourse.detail_id = CoursesDetail.id',
					'CoursesDetail.del_flg = 0'
				)
			),
			array(
				'table' => 'courses',
				'alias' => 'Course',
				'type' => 'inner',
				'conditions' => array(
					'CoursesDetail.course_id = Course.id',
					'Course.del_flg=0',
					'Course.display_flg = 1'
				),
			),
			array(
				'table' => 'profiles',
				'alias' => 'Profiles',
				'type' => 'left',
				'conditions' => array(
					'Course.user_id = Profiles.user_id','Profiles.del_flg = 0'
				),
			)		
		);
		$options['conditions'] = array(
				'EnteredCourse.user_id = '=> $user['id'],
				'EnteredCourse.del_flg = '=>0,
			);	
		
		if(isset($this->params['url']['coursetype'] ) && $this->params['url']['coursetype'] == 'willattend'){
			$options['conditions']['CoursesDetail.opening_date >'] = date('Y-m-d H:i:s');
			$enteredClass = '';
			$attendClass = 'selected';
		}else{
			$options['conditions']['CoursesDetail.opening_date <='] = date('Y-m-d H:i:s');
			$enteredClass = 'selected';
			$attendClass = '';
		}
		$this->paginate = $options;
		$courses = $this->paginate('EnteredCourse');
		$areas = $this->Area->find('list');
		$categories = $this->Category->find('list', array('fields' => array('Category.id', 'Category.rank')));
		$this->set('title_for_layout','マイページ');
		$this->set(array('courses' => $courses, 
			'enteredClass' => $enteredClass, 
			'attendClass' => $attendClass, 
			'areas' => $areas, 
			'category' => $categories,
			'title_for_layout' => 'マイページ - Adams Campus'
			));
	}

	/**
	 * action edit profile
	 */
	function profile(){
		$this->loadModel('Profile');
		$validatedType = Configure::read('Course.type');
		$userId = $this->CustomAuth->user('id');
		$uploadDir = Configure::read('User.upload_dir_prefix').DS.$userId;
		$allowImgType = str_replace('image/', '.', implode(', ', $validatedType)).', .jpg';
		$this->set(array('allowType' => $allowImgType));
		$this->set('title_for_layout', 'プロフィール編集画面 - Adams Campus');
		if(!is_dir($uploadDir)){
			mkdir($uploadDir, 0777);
		}else if(!is_writable($uploadDir)){
			chmod($uploadDir, 0777);
		}
		if(!empty($this->data)){
			$isUploadFile =is_uploaded_file($this->data['Profile']['icon_image']['tmp_name']);
			$avatar = $this->Session->read('User.icon_image');
			$this->Profile->set($this->data);
			if($this->Profile->validates()){//validate
				if($isUploadFile == true){//if upload avatar, delete old image, upload new image
					if(in_array($this->data['Profile']['icon_image']['type'], $validatedType)){
						if(($this->data['Profile']['icon_image']['size']/1024) < (Configure::read('User.max_icon_image_size')*1024) ){
							//get hash filename and extension
							try{
								list($fileNameMd5 , $extension) = $this->Profile->hashFileName($this->data['Profile']['icon_image']['name']);
								if(empty($fileNameMd5))
									$fileNameMd5 = md5(date('Y-m-d H:i:s'));
								if(empty($extension)){
									$extension = 'jpg';
								}
							}catch(Exception $e){
								$fileNameMd5 = md5(date('Y-m-d H:i:s'));
								$extension = 'jpg';
							}
							$fileName = $fileNameMd5 . '.'. $extension; //original image
							move_uploaded_file($this->data['Profile']['icon_image']['tmp_name'], $uploadDir.DS.$fileName);
							//create thumbnail image
							$isCrop = FALSE;
							try{
								$width = Configure::read('User.width_icon_image');
								$height = Configure::read('User.height_icon_image');
								$newFile = $fileNameMd5 . Profile::THUMB_SUFIX .'.'. $extension; //thumb image
								
								if($this->_makeThumbnailImage($uploadDir.DS.$newFile, $uploadDir.DS.$fileName, $width, $height)){
									$fileName = $newFile;
								}
							}catch(Exception $ex){
								throw $ex; // comment after debug
							}
							// end create thumnail
							$this->Profile->set('icon_image', $userId.'/'.$fileName);
							
							//delete old avatar
							$oldAvatar = Configure::read('User.upload_dir_prefix').DS.$avatar;
							$oldOriginalAvarta = Configure::read('User.upload_dir_prefix').DS. $this->Profile->getOriginalFileName($avatar);
							if(is_file($oldAvatar)){
								unlink($oldAvatar);
							}
							if(is_file($oldOriginalAvarta)){
								unlink($oldOriginalAvarta);
							}
							//end delete
							$avatar = $userId.'/'.$fileName;
						}else{
							$this->Profile->validationErrors['icon_image'] = 'allow file size < 100kb';
						}
					}else{
						$this->Profile->validationErrors['icon_image'] = 'only allow file '.implode(', ', $validatedType);
					}
				}else{
					unset($this->Profile->data['Profile']['icon_image']);
				}
				$this->Profile->set('description' , htmlspecialchars($this->data['Profile']['description']));
				$this->Profile->set('modified', date('Y-m-d H:i:s'));
				$this->Profile->set('id', $this->Session->read('profileId'));
				$this->Profile->set('first_name', htmlspecialchars($this->data['Profile']['first_name']));
				$this->Profile->set('last_name', htmlspecialchars($this->data['Profile']['last_name']));
				if($this->Session->read('profileId') === -1){
					$this->Profile->set('user_id', $userId);
				}
				if($this->Profile->save()){
					if($this->Session->read('profileId') === -1){
						$this->Session->write('profileId', $this->Profile->id);
					}
					$this->Session->write('User.name', $this->data['Profile']['last_name'].' '.$this->data['Profile']['first_name']) ;
					$this->Session->write('User.headline', $this->data['Profile']['headline']);
					$this->Session->write('User.icon_image', $avatar);
					$this->Session->setFlash(Messages::successfully);
					$this->redirect('mypage');
				}else{
					$this->Session->setFlash(Messages::error_please_try_again);
				}
			}else{
				
			}
		}else{
			try{
				$this->data = $this->Profile->findByUserId($userId);
				$this->Session->write('profileId', $this->data['Profile']['id'] ? $this->data['Profile']['id'] : -1);
			}catch(Exception $ex){

			}
		}
	}

	/**
	 * only make thumnail avatar , not check exists --> must check before call it :D
	 * @param string $newFile  : create newfile
	 * @param type $originalImage
	 * @param type $uploadDir // must create and writeable
	 * @param bool $isCrop : crop or resize image
	 */
	function _makeThumbnailImage($newFile, $originalImage, $width, $height){
		App::import('vendor', 'phpthumb'.DS.'src', array('file' => 'ThumbLib.inc.php'));
		try{
			$option = array('resizeUp' => true);
			$thumb = PhpThumbFactory::create($originalImage, $option);
			$dementions = $thumb->getCurrentDimensions();
			$mul = 1;
			if($dementions['width'] >= $width && $dementions['height'] >= $height){
				//$thumb->crop(0, 0, $width, $height);
				if($dementions['width'] < $dementions['height']){
					$mul = (float)$width/$dementions['width'];
				}else{
					$mul = (float)$height/$dementions['height'];
				}
			}else{
				if($dementions['width'] < $dementions['height']){
					$mul = (float)$width/$dementions['width'];
				}else{
					$mul = (float)$height/$dementions['height'];
				}
				
			}
			$thumb->resize(ceil($dementions['width']*$mul), ceil($dementions['height']*$mul) )->crop(0,0, $width, $height);
			
			//$thumb->adaptiveResizeQuadrant($width, $height, 'T|L');
			$thumb->save($newFile);
			return TRUE;
		}catch(Exception $ex){
			throw $ex;
		}
		return FALSE;
		
	}
	
	/*
	 * account action
	 * change email, set publish profile or not
	 */
	function account(){
		$this->loadModel('User');
		$userId = $this->CustomAuth->user('id');
		$this->set(array(
			'title_for_layout' => 'アカウント情報編集 - Adams Campus'
			));
		if(!empty($this->data)){
			$this->User->set($this->data);
			// unset all validate if need
			unset($this->User->validate['password']);
			if($this->data['User']['email'] == ''){
				unset($this->User->validate['email']);
				unset($this->User->data['User']['email']);
			}
			if($this->User->validates()){
				$this->User->set('id', $userId);
				if($this->User->save()){
					unset($this->data['User']['email']);
					$this->Session->setFlash(Messages::successfully);
				}else{
					$this->Session->setFlash(Messages::error_please_try_again);
				}
			}else{
				$this->Session->setFlash(Messages::validation_error);
			}
		}else{
			try{
				$this->data = $this->User->findById($userId);
				unset($this->data['User']['email']);
			}catch(Exception $ex){
				error_log('loi page account : '.$ex);
			}
		}
	}
	
	/*
	 * change password action
	 */
	function password(){
		$userId = $this->CustomAuth->user('id') ;
		if ($this->RequestHandler->isPost()) {
			$this->loadModel('PasswordForm');
			$this->PasswordForm->set($this->data);
			if ($this->PasswordForm->validates()) {
				$password = $this->data['PasswordForm']['password'];
				$this->loadModel('User');
				$user = $this->User->read(null, $userId);
				$user['User']['password'] = $this->CustomAuth->password($password);
				$this->User->save($user, false);
				$this->Session->setFlash(Messages::your_password_has_been_changed_try_logout_and_login_again_to_test_your_new_password);
				$this->redirect(array('controller' => 'users', 'action' => 'password'));
			}
		}
		$this->set(array(
			'title_for_layout' => 'パスワード変更 - Adams Campus'
			));
	}
	
    /**
     *function send email 
     */
    function _sendUserEmail($userName, $email){
        $this->_initEmail();
        $this->Email->to = $email;
        $this->Email->subject = '【Adams campus】ご登録ありがとうございます';
        $this->Email->template = 'signup';
        $this->set(array(
            'userName' => $userName,
            'email' => $email,
        ));
        $this->Email->send();
    }
    
	/*
	 * create Facebook instant
	 */
	function _getFacebookObject() {
		Configure::load('facebook');
		App::import('vendor', 'facebook/src/facebook');
		$appId = Configure::read('facebook.appid');
		$serect_id = Configure::read('facebook.serectkey');
		$facebook = new Facebook(array(
			'appId' => $appId,
			'secret' => $serect_id,
		));
		return $facebook;
	}

	/**
	 * Verify login status, if user have login, redirect to home page
	 */
	function _checkLogin() {
		$roles = Configure::read('roles');
		if($this->Session->read($this->CustomAuth->sessionKey) && in_array($this->CustomAuth->user('role'), $roles) ){
			$this->redirect('/');
		}
	}
	
	/*
	 * redirect after login or sigup success
	 */
	function _successRedirect()
	{
		if($this->Session->check('Auth.redirect')){
			$url = $this->Session->read('Auth.redirect');
			$this->Session->delete('Auth.redirect');
			$this->redirect($url);
		}else{
			/*if($this->Session->check('referUrl')){
				$this->redirect($this->Session->read('referUrl'));
			}*/
			$this->redirect('/users/mypage');
		}
	}
	/*
	 * get facebook avatar
	 */
	function _getFacebookAvatar($facebookUrl, $localDir, $userId)
	{
		
		if(!is_dir($localDir)){
			mkdir($localDir, 0777, true);
			chmod($localDir, 0777);
		}else if(!is_writable($localDir)){
			chmod($localDir, 0777);
		}
		$fileNameMd5 = md5(date('Y-m-d H:i:s'));
		$fileName = $fileNameMd5.'.jpg';
		$avatarUrl = $localDir.DS.$fileName;
		try{			
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $facebookUrl);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_HEADER, false);
			$response = curl_exec($ch);
			$error = curl_errno($ch);
			if($error === 0){
				$data = json_decode($response);
				if(is_object($data)){
					$imageUrl = $data->data->url;
					$newFile = fopen($avatarUrl, 'wb');
					curl_setopt($ch, CURLOPT_URL, $imageUrl);
					curl_setopt($ch, CURLOPT_FILE, $newFile);
					curl_exec($ch);
					curl_close($ch);
					fclose($newFile);
					try{
						$width = Configure::read('User.width_icon_image');
						$height = Configure::read('User.height_icon_image');
						$newFile = $fileNameMd5 . Profile::THUMB_SUFIX .'.jpg'; //thumb image

						if($this->_makeThumbnailImage($localDir.DS.$newFile, $avatarUrl, $width, $height)){
							$fileName = $newFile;
						}
					}catch(Exception $ex){
						return $userId.'/'.$fileName;
					}
					return $userId.'/'.$fileName;
				}else{
					//call get image url by header
					curl_close($ch);
				}
			}else{
				//call get image url by header
				curl_close($ch);
			}
		}catch(Exception $ex)
		{
			throw $ex;
		}
		return '';
	}

	/**
	 * Controller for left_user_profile element
	 *
	 * @return array
	 */
	function leftUserProfile() {
		if (isset($this->params['requested'])) {
			$nbClassEntered = $this->_getEnteredClassNumber();
			$nowPoint = $this->CustomAuth->user('now_point');
			return array($nbClassEntered, $nowPoint);
		}
		$this->cakeError('error404');
	}

	/**
	 * Forgot password action
	 * @return string
	 */
	function reminder() {
		$this->_checkLogin();
		$this->loadModel('ReminderForm');
		if (isset ($this->params['url']['view'])) {
			if ($this->params['url']['view'] == 'success') {
				return $this->render('reminder_success');
			} else {
				return $this->render('reminder_error');
			}
		}
		if ($this->RequestHandler->isPost()) {
			$this->ReminderForm->set($this->data);
			if ($this->ReminderForm->validates()) {
				$this->loadModel('user');
				$options = array(
					'conditions' => array(
						'email' => $this->data['ReminderForm']['email'],
					)
				);
				$user = $this->User->find('first', $options);
				if ($user) {
					$password = $this->User->generatePassword();
					$user['User']['password'] = $this->CustomAuth->password($password);
					$user['User']['modified'] = date('Y-m-d H:i:s');
					$this->User->save($user, false);
					$this->_initEmail();
					$this->Email->to = $user['User']['email'];
					$this->Email->subject = '【Adams campus】パスワードのリセットを行いました';
					$this->Email->template = 'reminder';
					$this->set(array(
						'user' => $user,
						'password' => $password,
					));
					$this->Email->send();
					$view = 'success';
				} else {
					$view = 'error';
				}
			} else {
				$view = 'error';
			}
			$this->redirect(array('controller' => 'users', 'action' => 'reminder', '?' => array('view' => $view)));
		}
	}

	/**
	 * Using for get list of user, display on index page
	 */
	function getTopUser() {
		if (isset($this->params['requested'])) {
			return $this->User->getTopUser();
		} else {
			$this->cakeError('error404');
		}
	}
}

?>
